#!/bin/bash
# 修复并重启 CMDB 服务

echo "=========================================="
echo "   CMDB 修复并重启"
echo "=========================================="
echo ""

# 停止现有服务
echo "🛑 停止现有服务..."
pkill -f "daphne.*backend.asgi" 2>/dev/null
pkill -f "vite" 2>/dev/null
sleep 2

# 清理并重建日志目录
echo "🧹 清理日志目录..."
rm -rf /aiops/logs
mkdir -p /aiops/logs
touch /aiops/logs/backend.log
touch /aiops/logs/frontend.log

# 启动后端
echo "🚀 启动后端服务..."
cd /aiops
. .venv/bin/activate
cd backend
nohup daphne -b 0.0.0.0 -p 8000 backend.asgi:application > /aiops/logs/backend.log 2>&1 &
BACKEND_PID=$!
echo $BACKEND_PID > /aiops/logs/backend.pid
cd /aiops

# 等待后端启动
echo "⏳ 等待后端启动..."
for i in {1..10}; do
    if curl -s http://localhost:8000/admin/ > /dev/null 2>&1; then
        echo "✅ 后端已启动 (PID: $BACKEND_PID)"
        break
    fi
    sleep 1
    echo -n "."
done
echo ""

# 启动前端
echo "🚀 启动前端服务..."
cd /aiops/frontend
nohup npm run dev > /aiops/logs/frontend.log 2>&1 &
FRONTEND_PID=$!
echo $FRONTEND_PID > /aiops/logs/frontend.pid
cd /aiops

# 等待前端启动
echo "⏳ 等待前端启动..."
for i in {1..15}; do
    if curl -s http://localhost:8080 > /dev/null 2>&1; then
        echo "✅ 前端已启动 (PID: $FRONTEND_PID)"
        break
    fi
    sleep 1
    echo -n "."
done
echo ""

echo "=========================================="
echo "   ✅ 服务已重启"
echo "=========================================="
echo ""
echo "前端: http://localhost:8080"
echo "后端: http://localhost:8000/api/"
echo "Admin: http://localhost:8000/admin/"
echo ""
echo "运行 'bash check.sh' 验证服务状态"
echo ""
